<template>
  <el-form :model="userData" :rules="rules" ref="form" class="layout">
    <div class="pictur">
      <img :src="userData.avatarUrl" style="height: 80px; width: 80px;">
      <el-upload class="upload-demo" :show-file-list="false" :http-request="handlehttpRequest"
        :before-upload="beforeAvatarUpload">
        <el-button>更换头像</el-button>
      </el-upload>
    </div>
    <div class="user">
      <div style="display: flex; flex-direction: column;">
        <el-form-item prop="name" label="姓名" :rules="[{ required: true, message: '姓名不能为空', trigger: 'blur' }]">
          <el-input v-model="userData.name" style="width: 350px;height: 30px;" />
        </el-form-item>
      </div>
    </div>
    <div class="user1">
      <div style="display: flex; flex-direction: column;">
        <el-form-item prop="phoneNumber" label="手机号码"
          :rules="[{ required: true, message: '手机号码不能为空', trigger: 'blur' }]">
          <el-input v-model="userData.phoneNumber" style="width: 350px;height: 30px;" />
        </el-form-item>
      </div>
    </div>
    <div class="use2">
      <div style="display: flex; flex-direction: column;">
        <el-form-item prop="email" label="邮箱" :rules="[{ required: true, message: '邮箱不能为空', trigger: 'blur' }]">
          <el-input v-model="userData.email" style="width: 350px;height: 30px;" />
        </el-form-item>
      </div>
    </div>
    <div style="text-align: center; margin-top: 20px;">
      <el-button type="primary" @click="submitForm">提交</el-button>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { useUserStore } from '@/stores';
import { computed } from 'vue';
import { ElForm, ElMessage, ElMessageBox, type UploadProps } from 'element-plus';
import { uploadFileApi } from '@/api/File/upload';
import { updateAdminInfo } from '@/api/My';
import type { AdminInfo } from '@/api/My';
import type { UserInfo } from '@/stores/store/user';

const userStore = useUserStore();
const userInfo = computed(() => userStore.getUserInfo());
//表单
const userData = ref({
  id: userInfo.value?.id,
  avatarUrl: userInfo.value?.avatarUrl,
  name: userInfo.value?.name,
  phoneNumber: userInfo.value?.phoneNumber,
  email: userInfo.value?.email
});
//验证规则
const rules = {
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { pattern: /^[1][3-9][0-9]{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
};
//上传之前校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!');
    return false;
  }
  return true;
}
//上传图片
const handlehttpRequest: UploadProps['httpRequest'] = async (options) => {
  const formData = new FormData();
  formData.append('file', options.file);

  try {
    const response = await uploadFileApi(options.file);
    userData.value.avatarUrl = response.data.data;
    if (response.data) {
      ElMessage.success('文件上传成功！');
    } else {
      ElMessage.error('文件上传失败！');
    }
  } catch (error) {
    console.error('上传文件失败:', error);
    ElMessage.error('上传文件失败，请重试');
  }
}
const submitForm = async () => {
  ElMessageBox.confirm(
    '确认提交更新的个人信息吗？',
    '确认提交',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    if (userData.value.id) {
      const response = await updateAdminInfo(userData.value as AdminInfo);
      if (response.data.code === 1) {
        ElMessage.success('更新成功！');
        userStore.setUserInfo(userData.value as UserInfo);
      } else {
        ElMessage.error('更新失败！');
      }
    }
  }).catch(() => {
    ElMessage.info('取消提交');
  });
}
</script>

<style lang="scss" scoped>
.layout {
  display: flex;
  flex-direction: column;
}

.pictur {
  margin-top: 50px;
  width: 90px;
  text-align: center;
  margin-left: 120px;
}

.user {
  display: flex;
  margin-left: 50px;
  align-items: center;
  margin-top: 20px;
}

.user1 {
  display: flex;
  margin-left: 22px;
  align-items: center;
}

.use2 {
  display: flex;
  margin-left: 50px;
  align-items: center;
}
</style>
